package com.java.androidmarket.interceptor;

import com.alibaba.fastjson.JSON;
import com.google.common.util.concurrent.RateLimiter;
import com.java.androidmarket.entity.Result;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description:
 * author:张腾
 * date:2021-07-13
 */

public class RateLimiterInterceptor implements HandlerInterceptor {

    private final RateLimiter rateLimiter;

    public RateLimiterInterceptor(RateLimiter rateLimiter) {
        this.rateLimiter = rateLimiter;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (this.rateLimiter.tryAcquire()){
            return true;
        }
        Result result = new Result();
        result.setCode("-1").setMsg("抢购失败请重试");
        response.setContentType("application/json;charset=UTF-8");
        String json = JSON.toJSONString(result);
        response.getWriter().println(json);
        return false;
    }
}
